/**
 * @file
 * @auth jinguangguo
 * @date 2017/5/11
 */

import Vue from 'vue';

import filter from '../../../../../grsc-base/util/filter';
import Pager from '../../../../../grsc-base/component/Pager.vue';
import VSelect from '../../../../../grsc-base/component/Select.vue';
import Loading from '../../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../../grsc-base/component/NoData.vue';
import service from '../service';
import commonService from '../../../../common/commonService';
import assetConfig from '../../../../common/assetConfig';
import {
    PAGE_SIZE,
    REG_NUMBER,
    REG_EN
} from '../../../../../grsc-base/common/constants';
import parseUrl from '../../../../../grsc-base/util/parseUrl';

import verifyCodeMixin from '../../../../mixins/verifyCodeMixin';
import MathTool from '../../../../../grsc-base/util/mathtool';
import Popover from '../../../../../grsc-base/component/Popover.vue';
import Validator from '../../../../../grsc-base/component/Validator/main';
import VerifyCode from '../../../../component/VerifyCode.vue';
import util from '../../../../common/util';
import AssetDrop from '../AssetDrop.vue'
import setPayPwd from '../../../../component/setPayPwd/main';

export default Vue.extend({
    mixins: [verifyCodeMixin],
    components: {
        Pager,
        Loading,
        NoData,
        VSelect,
        Popover,
        Validator,
        VerifyCode,
        AssetDrop,
        setPayPwd
    },

    created() {
        this.coinType = localStorage.getItem('cointype2')
        this.fetchCoinAddressList();
        this.initFee();
        this.queryGoogleStatus();
        this.fetchList();
        this.fetchPayPsdStatus();
    },

    data() {
        let query = parseUrl();
        let currentAddress = '';
        if (query.address) {
            currentAddress = query.address;
        }
        let amountRule = {
            tip: this.$t('asset.available') + ': --',
            required: true,
            requiredTip: this.$t('asset.withdraw.volumeRequrireTip'),
            min: 0,
            minTip: ''
        };
        return {
            coinType: '',

            isLoading: true,
            fee: 0,
            precision: 0,
            filter: filter,
            coinBalance: '--',
            coinLock: '--',
            pageNo: 1,
            pageSize: PAGE_SIZE,
            pageNum: 0,
            // currentAddress: currentAddress,
            coinAddressList: [{
                val: '',
                label: this.$t('asset.withdraw.chooseAddress')
            }],
            addressError: false,
            uidError: false,
            btcPrice: '--',
            usdPrice: '--',
            form: {
                message: '',
                amount: '',
                address: currentAddress,
                paypwd: '',
                identifyingCode: '',
                uid: '',
            },
            rules: {
                address: {
                    required: true
                },
                amount: amountRule,
                paypwd: {
                    required: true,
                    requiredTip: this.$t('common.assetPassRequireTip')
                },
                identifyingCode: {
                    required: true,
                    requiredTip: this.$t('common.verifyCodeRequireTip'),
                    pattern: /^\d{6}$/,
                    patternTip: this.$t('common.IncorrectverifyCodeTip')
                },
                uid: {
                    required: true,
                    requiredTip: this.$t('asset.withdraw.uidTip'),
                }
                // identifyingCode: {
                //     required: true,
                //     requiredTip: this.$t('common.verifyCodeRequireTip'),
                //     pattern: /^\d{6}$/,
                //     patternTip: this.$t('common.IncorrectverifyCodeTip')
                // }
            },
            isRequesting: false,
            list: null,
            coinList: null,
            googleStatus: 'OFF',
            isShowSetPayPwd: true,
        };
    },
    methods: {

        initFee() {
            console.log(this.coinType)
            this.precision = this.$$assetMap[this.coinType][assetConfig.WITHDRAWPRECISION];
            this.rules.address.requiredTip = this.$t('common.coinAddressRequireTip', {
                coin: this.coinType
            });

            this.fetchWithdrawFee();
            this.fetchWithdrawMin();
        },


        /**
         * 获取转出手续费
         */
        fetchWithdrawFee() {
            service.withdrawFee({
                key: 'WITHDRAWMINFEE',
                assetCode: this.coinType
            }).done((rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.fee = rep.data.profileValue
                } else {
                    window.error(rep.msg);
                }
            })).fail((rep => {

            }));
        },

        /**
         * 获取最低转出额度
         */
        fetchWithdrawMin() {
            let minNum;
            service.withdrawFee({
                key: 'WITHDRAWMIN',
                assetCode: this.coinType
            }).done((rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    minNum = rep.data.profileValue;
                    this.rules.amount.min = minNum;
                    this.rules.amount.minTip = this.$t('asset.withdraw.withdrawVolumeTip', {
                        num: minNum,
                        coin: this.coinType
                    });
                } else {
                    window.error(rep.msg);
                }
            })).fail((rep => {

            }));
        },


        /**
         * 获取转出地址列表
         * */
        fetchCoinAddressList() {
            let that = this;
            let param = {
                assetCode: this.coinType||localStorage.getItem('cointype2'),
                pageNo: 1,
                pageSize: 5
            };
            service.transferOutAddressQuery(param).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    if (rep.data.list.length === 0) {
                        this.coinAddressList = [{
                            val: '',
                            label: this.$t('asset.withdraw.noAddress')
                        }];
                    } else {
                        this.coinAddressList = formatAddress(rep.data.list);
                    }
                }
            });

            function formatAddress(list) {
                let templist = [{
                    val: '',
                    label: that.$t('asset.withdraw.chooseAddress')
                }];
                $.map(list, (item, index) => {
                    let len = item.address.length;
                    if (len > 10) {
                        item.addressText = item.address.substr(0, 6) + '......' + item.address.substr(len - 4, len - 1)
                    } else {
                        item.addressText = item.address;
                    }
                    templist.push({
                        val: item.address,
                        label: `<span class="fn-bold">${item.memo}</span>（${ item.addressText}）`
                    });
                });
                return templist;
            }
        },

        onChangeAddress(address) {
            this.form.address = address;
            this.addressError = false;
        },


        queryGoogleStatus() {
            let googleBound = window.localStorage.getItem('GOOGLE_BOUND');
            let googleStatus = window.localStorage.getItem('GOOGLE_STATUS');

            if (googleBound === 'true' && googleStatus === 'ON') {
                this.googleStatus = googleStatus;
                this.form.googleCode = '';
                this.rules.googleCode = {
                    required: true,
                    requiredTip: this.$t('common.googleCodeRequireTip'),
                    pattern: '\\d{6}',
                    patternTip: window.CODE.GOOGLE_CODE[this.$i18n.locale]
                };
            } else {
                this.googleStatus = 'OFF';
            }
        },

        onSendSuccess() {
            this.rules.identifyingCode.$setRight(this.$t('common.codeSentTip'));
        },
        onSendFail(rep) {
            this.rules.identifyingCode.$setError(rep.msg);
        },

        /**
         * 获取转出历史列表
         */
        fetchList() {
            this.isLoading = true;
            service.transferOutHistory({
                assetCode: this.coinType,
                pageNo: this.pageNo,
                pageSize: PAGE_SIZE
            }).done((rep) => {
                this.isLoading = false;
                if (rep.code == window.CODE.SUCCESS) {
                    this.list = rep.data.list;
                    this.pageNum = rep.data.pageNum;
                } else {
                    window.error(rep.msg);
                }
            }).fail((rep) => {

            }).always(() => {
                this.isLoading = false;
            });
        },


        /**
         * 分页change
         * @param currentPage
         */
        changePage(currentPage) {
            this.pageNo = currentPage;
            this.fetchList();
        },

        /**
         * 全部转出
         * */
        drawOutAll() {
            this.form.amount = this.coinBalance;
        },

        checkAddress() {
            if (this.uidShow) {
                if (this.form.uid.length <= 0) {
                    this.uidError = true;
                    return false;
                }
                return true;
            } else {
                if (this.form.address.length <= 0) {
                    this.addressError = true;
                    return false;
                }
                return true;
            }
        },

        /**
         * 提交表单
         */
        submit() {   
            let param = {
                assetCode: this.coinType,
                amount: this.form.amount,
                message: this.form.message,
                outOrder: util.getUuid(),
                fee: this.fee
            };
            if (this.uidShow) {
                param.depositUid = Number(this.form.uid + '');
            } else {
                param.address = this.form.address;
            }
            let url = this.uidShow == false ? 'transferOut' : 'transferInner';
            if(url == 'transferOut') {
                if(!param.address) {
                    return window.error('地址不能为空')
                }
                if(!param.amount) {
                    return window.error('数量不能为空')
                }           
                if(!this.form.paypwd) {
                    return window.error('密码不能为空')
                }
            } else {
                if(!param.depositUid) {
                    return window.error('ID不能为空')
                }
                if(!param.amount) {
                    return window.error('数量不能为空')
                }           
                if(!this.form.paypwd) {
                    return window.error('密码不能为空')
                }
            }
            
            this.isRequesting = true;
            let header = {
                'pay-password': this.form.paypwd,
                'service-code': this.form.identifyingCode
            };
            if (this.googleStatus === 'ON') {
                header['google-code'] = this.form.googleCode
            }
            service[url](param, header).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    window.success(this.$t('asset.withdraw.withdrawSuccessTip', {coin: this.coinType}), () => {
                        this.reload();
                    }, 4000);
                } else if (rep.code === window.CODE.IDENTIFY.CODE) {
                    window.error(window.CODE.IDENTIFY[this.$i18n.locale]);
                } else if (rep.code === window.CODE.IDENTIFY_INVALID.CODE) {
                    window.error(window.CODE.IDENTIFY_INVALID[this.$i18n.locale]);
                } else if (rep.code === window.CODE.CURRENCY_NOT_ENOUGH.CODE) {
                    window.error(window.CODE.CURRENCY_NOT_ENOUGH[this.$i18n.locale]);
                } else if (rep.code === window.CODE.PAY_PWD.CODE) {
                    let num = rep.data.num;
                    if (3 - num > 0) {
                        window.error(this.$t('common.IncorrectAssetPassTip',{num: 3-num}));
                    } else {
                        window.error(window.CODE.PAY_PWD_LOCK[this.$i18n.locale]);
                    }
                } else if (rep.code === window.CODE.PAY_PWD_LOCK.CODE) {
                    window.error(window.CODE.PAY_PWD_LOCK[this.$i18n.locale]);
                } else if (rep.code === window.CODE.COIN_ASSERT_LESS.CODE) {
                    window.error(window.CODE.COIN_ASSERT_LESS[this.$i18n.locale], () => {
                        this.reload();
                    }, 4000);
                } else if (rep.code === window.CODE.GOOGLE_CODE.CODE){
                    window.error(window.CODE.GOOGLE_CODE[this.$i18n.locale]);
                } else {
                    window.error(rep.msg);
                }
            }).fail((rep) => {
                window.error(rep.msg);
            }).always(() => {
                this.isRequesting = false;
            });

        },

        changeCoinType(coinType) {
            this.coinType = coinType;
            console.log(this.coinType)
            this.initFee();
            this.getTotalAssets();
            this.queryGoogleStatus();
            this.fetchList();
            this.fetchCoinAddressList();
        },

        fetchPayPsdStatus() {
            commonService.basic().done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.isShowSetPayPwd = rep.data.setPayPassword;
                    // this.UID = rep.data.uid;
                } else {
                    window.toast(rep.msg);
                }
            })
        },
    }
});